<template>
    <div class="table-all"">
        <!-- 搜索区 -->
        <div class="app-container search-box">
            <SearchForm
                    :form="searchData.form"
                    :options="searchData.options"
                    @searchUpdate="search"
                    @resetSearchData="resetSearchData"
            ></SearchForm>
        </div>
        <!-- 按钮区 -->
        <div class="app-container table-box">
            <div class="table-main">
                <!-- 表格 -->
                <v-table
                  title="危险源详情数据"
                        v-if="tableMainHeight>0"
                        :table-columns="tableColumns"
                        :table-data="tableData"
                        :loading="loading"
                        :is-index="true"
                        ref="table"
                        :maxHeight="tableMainHeight">
                    <template #topButtonList>
                        <ButtonForm :buttonList="buttonList" @clickButton="clickButton"></ButtonForm>
                    </template>
                    <template #bClassify="scope">
                            {{getDictValue(scope.row.bclassify, bClassifyOptions)}}


                    </template>
                    <template #sClassify="scope">
                            {{getDictValue(scope.row.sclassify, sClassifyOptions)}}
                    </template>
                    <template #grade="scope">
                            {{getDictValue(scope.row.grade, gradeOptions)}}
                    </template>
                    <template #operation="scope">
                      <a v-hasPermission="['riskSource:add']" class="table-btn-edit table-operation"
                         @click="handleEdit(scope.row)">{{$t('table.edit')}}</a>
                      <a v-hasPermission="['riskSource:detail']" class="table-btn-view table-operation"
                         @click="handleDetail(scope.row)">{{$t('table.view')}}</a>
                      <a v-hasPermission="['riskSource:delete']" class="table-btn-delete table-operation"
                         @click="singleDelete(scope.row)">{{$t('table.delete')}}</a>
                    </template>
                </v-table>
            </div>
            <div class="table-page">
                <!-- 页码 -->
                <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize"
                            @pagination="search"/>
            </div>
        </div>
        <!-- 详情 -->
        <detailDialog :dialog-visible="detailDialogShow"
                    @success="editSuccess"
                    @close="editClose"
                    :openType="detailOpenType"
                    :id="detailId"
                    :title="detailTitle"
        ></detailDialog>
        <tableImportDialog
          ref="importDialog"
          :dialog-visible.sync="importDialog.isVisible"
          :title="importDialog.title"
          :template-list="importTemplateList"
          :uploadOptions="uploadOptions"
        />
    </div>
</template>

<script>
    import { riskSourcePage,
            riskSourceExport,
            riskSourceDelete,
            riskSourceTemplate,
            riskSourceImport
    } from '@/api/risk/riskSource'

    import SearchForm from '@/components/searchForm/index'
    import ButtonForm from '@/components/ButtonForm/index'
    import VTable from '@/components/VTable/index'
    import Pagination from '@/components/Pagination/index'
    import detailDialog from './detail.vue'
    import tableImportDialog from '@/components/TableImportDialog/tableImportDialog'
    export default {
        components:{
            VTable,Pagination,detailDialog,SearchForm,ButtonForm,tableImportDialog
        },
        data(){
            return{

              importDialog:{
                isVisible: false,
                title: '危险源详情信息'
              },
              importTemplateList: [
                {
                  label: '下载导入模板',
                  url: '/risk/riskSource/template',
                  downloadFileName: '危险源详情信息.xlsx',
                  // clickFn: this.downloadTemplate, //选填项，点击下载按钮时触发，如果想自己手动实现下载，可在这里定义方法，否则使用默认的下载方法
                },
              ],
              uploadOptions: {
                accept: '.xlsx', //限制文件格式，多个用逗号隔开如：'.xlsx,.png'
                uploadTextTip: '请上传excel文件,以.xlsx为后缀',
                url: '/risk/riskSource/import',
                // uploadFn: this.handleUpload, //选填项，点击确认时触发上传，如果想自己手动实现上传，可在这里定义方法，否则使用默认的上传方法
                successFn: this.handleUploadSuccess, //选填项，上传成功后触发
              },

                tableColumns:[

                            // {
                            //   prop: 'flagCode',
                            //   label: '标识码',
                            //   minWidth: '150',
                            //   slotname: 'flagCode',
                            //   options: {}
                            // },
                            {
                                prop: 'bclassify',
                                label: '危险源大类',
                                minWidth: '150',
                                slotname: 'bClassify',
                                options: {}
                            },
                            {
                                prop: 'sclassify',
                                label: '危险源细类',
                                minWidth: '150',
                                slotname: 'sClassify',
                                options: {}
                            },
                            {
                                prop: 'name',
                                label: '危险源名称',
                                minWidth: '150',
                                slotname: 'name',
                                options: {}
                            },
                            {
                                prop: 'grade',
                                label: '危险源等级',
                                minWidth: '150',
                                slotname: 'grade',
                                options: {}
                            },

                            {
                              prop: 'areaCode',
                              label: '所在地市',
                              minWidth: '150',
                              slotname: 'areaCode',
                              options: {}
                            },

                            {
                              prop: 'address',
                              label: '危险源地址',
                              minWidth: '150',
                              slotname: 'address',
                              options: {}
                            },

                            {
                                prop: 'unit',
                                label: '主管单位',
                                minWidth: '150',
                                slotname: 'unit',
                                options: {}
                            },
                            {
                                prop: 'unitName',
                                label: '主管单位负责人',
                                minWidth: '150',
                                slotname: 'unitName',
                                options: {}
                            },
                            {
                                prop: 'unitAddress',
                                label: '主管单位地址',
                                minWidth: '150',
                                slotname: 'unitAddress',
                                options: {}
                            },
                            {
                                prop: 'receiveTime',
                                label: '数据收集时间',
                                minWidth: '150',
                                slotname: 'receiveTime',
                                options: {}
                            },
                            {
                                prop: 'receiveName',
                                label: '数据收集人',
                                minWidth: '150',
                                slotname: 'receiveName',
                                options: {}
                            },
                    {
                        prop: 'operation',
                        label: '操作',
                        width: '200',
                        align: 'center',
                        slotname: 'operation',
                        overflow: false,
                        fixed: 'right'
                    }
                ],
                tableData:[],
                selection: [],
                loading:false,
                total:1,
                pageNum:1,
                pageSize:10,
                detailOpenType:"add",
                detailDialogShow:false,
                detailId:"",
                detailTitle:"新增",
                dict:{},
                searchData:{
                  form:{
                        bClassify:'',
                        sClassify:'',
                        name:'',
                        grade:'',
                        areaCodeAll:[],
                        provinceCode:"",
                        cityCode:"",
                        countyCode:"",
                },
                   options:[

                           {
                             title: "行政区划",
                             key: "areaCodeAll",
                             type: "gdAreaSelect",
                             changeFn: this.searchAreacodeHandle, //如需对区域数据做更多的处理，可在这里定义方法
                           },
                             {
                                 title:"危险源大类",
                                 key: "bclassify",
                                 type: "select",
                                 multiple:false,
                                 option: {
                                     data: this.bClassifyOptions,
                                     props: {
                                         key: "id", // 指定key对应data的字段
                                         label: "label", // 指定label对应data的字段
                                         value: "name", // 指定value对应data的字段
                                     },
                                 },
                             },
                             {
                                 title:"危险源细类",
                                 key: "sclassify",
                                 type: "select",
                                 multiple:false,
                                 option: {
                                     data: this.sClassifyOptions,
                                     props: {
                                         key: "id", // 指定key对应data的字段
                                         label: "label", // 指定label对应data的字段
                                         value: "name", // 指定value对应data的字段
                                     },
                                 },
                             },
                             {
                                 title:'危险源名称',
                                 key: "name",
                                 type: "text",
                             },
                             {
                                 title:'危险源等级',
                                 key: "grade",
                                 type: "select",
                                 multiple:false,
                                 option: {
                                     data: this.gradeOptions,
                                     props: {
                                         key: "id", // 指定key对应data的字段
                                         label: "label", // 指定label对应data的字段
                                         value: "name", // 指定value对应data的字段
                                     },
                                 },
                             },
                   ]
                },
                buttonList:[
                    {name:'新增',methods:'handleAdd',type:'primary',haspremission:['riskSource:add']},
                    //{name:'导入',methods:'handleImport'},
                    //{name:'导出',methods:'handleExport'}
                ],
                tableMainHeight: 0,
                // 字典
                bClassifyOptions:[],
                sClassifyOptions:[],
                gradeOptions:[],
            }
        },
        watch: {
            // 字典
                    'bClassifyOptions':{
                        handler(newVal, oldVal) {
                            this.searchData.options.forEach(t=>{
                                if(t.key=='bclassify'){
                                t.option.data = newVal
                            }
                        })
                        },
                        deep: true,
                        immediate: true
                    },
                    'sClassifyOptions':{
                        handler(newVal, oldVal) {
                            this.searchData.options.forEach(t=>{
                                if(t.key=='sclassify'){
                                t.option.data = newVal
                            }
                        })
                        },
                        deep: true,
                        immediate: true
                    },
                    'gradeOptions':{
                        handler(newVal, oldVal) {
                            this.searchData.options.forEach(t=>{
                                if(t.key=='grade'){
                                t.option.data = newVal
                            }
                        })
                        },
                        deep: true,
                        immediate: true
                    },
        },
        methods:{


          handleDownload(data){
            let fileName = "危险源详情信息导入模板.xlsx"
            return riskSourceTemplate(data, fileName)
          },
          handleUpload(file){
            // console.log("file",file)
            const formData = new FormData()
            formData.append('file', file)
            //   formData.append('file', fileList[0].raw)
            //   console.log("formData,==",formData.get("file"))
            riskShelterImport(formData)
              .then((res) => {
                if (res.code === 200) {
                  this.$message.success('导入成功')
                  this.search()
                  this.importDialog.isVisible = false
                }
              })
              .finally(() => {
                this.$refs.importDialog.clearFileList()
              })
          },
          handleUploadSuccess(){
            this.search()
            this.importDialog.isVisible = false
          },
          handleClose() {
            this.importDialog.isVisible = false
          },

            getCheckBoxValue(value,option){
                if(!value){
                    return
                }
                let temp = []
                let data = value.split(",")
                data.forEach(t=>{
                    let item = option.find(x=> x.value == t)
                if(item != undefined){
                    temp.push(item.label)
                }
            })
                return temp.join(",")
            },
            getDictValue(value,option){
                let item = option.find(t=> t.value == value)
                if(item!=undefined){
                    return item.label
                }
                return value
            },
            editClose(){
                this.detailDialogShow = false
            },
            editSuccess(){
                this.search()
                this.detailDialogShow = false
            },
            search(){
                this.fetch({
                        ...this.searchData.form,
                })
            },
            fetch(params={}){
                params.pageSize = this.pageSize
                params.pageNum = this.pageNum
                this.loading = true
                 riskSourcePage(params).then(async res=>{
                    if(res.code==200){
                      this.total = res.data.total
                      let rows = res.data.rows
                      for(let item of rows){
                        item.areaCode = await this.$commonJs.areaCodeToName(item)
                      }
                      this.tableData = res.data.rows
                    }else{
                    this.$message({
                        message: this.$t('tips.systemException'),
                        type: 'error'
                     })
                   }
                }).finally(final=>{
                    this.loading = false
               })
            },
            // 重置搜索条件
            resetSearchData(){
                this.searchData.form = {
                        bClassify:'',
                        sClassify:'',
                        name:'',
                        grade:'',
                        areaCodeAll:'',
                        provinceCode:"",
                        cityCode:"",
                        countyCode:"",
                }
            },
            searchAreacodeHandle(arr){
              console.log(arr)
              this.searchData.form.provinceCode=arr[0]
              this.searchData.form.cityCode=arr[1]
              this.searchData.form.countyCode=arr[2]
            },

            // 触发按钮区域按钮方法
            clickButton(methods){
                this[methods]()
            },
            handleAdd(){
                this.detailOpenType = "add"
                this.detailTitle = "新增"
                this.detailDialogShow = true
            },

            handleEdit(row){
              this.detailId = row.id
              this.detailOpenType = "edit"
              this.detailTitle="编辑"
              this.detailDialogShow = true
            },
            handleDetail(row){
              this.detailId = row.id
              this.detailOpenType = "detail"
              this.detailTitle="详情"
              this.detailDialogShow = true
            },
            handleExport(){
                let params = {
                        ...this.searchData.form
                }
                riskSourceExport(params,`危险源详情信息_${new Date().getTime()}.xlsx`);
            },
            handleImport(){
              console.log("等待处理")
              this.importDialog.isVisible = true
            },


            closeDialog(){
              this.detailDialogShow = false
            },

            singleDelete(row){
                this.$confirm(this.$t('tips.confirmDelete'), this.$t('common.tips'), {
                    confirmButtonText: this.$t('common.confirm'),
                    cancelButtonText: this.$t('common.cancel'),
                    type: 'warning'
                }).then(() => {
                    this.loading = true
                    riskSourceDelete(row.id).then(res=>{
                    if(res.code==200){
                    this.$message({
                        message: this.$t('tips.deleteSuccess'),
                        type: 'success'
                    })
                    this.search()
                     }else{
                        this.$message({
                            message: this.$t('tips.systemException'),
                            type: 'error'
                        })
                    }
                 }).finally(final=>{
                    this.loading = false
                 })
                })
            }
        },
        activated(){
            this.fetch()
        },
        created(){
            // 获取字典值
          this.bClassifyOptions = []
          this.$commonJs.filterDataDict("riskBClassify",this.bClassifyOptions )

          this.sClassifyOptions=[]
          this.$commonJs.filterDataDict("riskSClassify",this.sClassifyOptions )


          this.gradeOptions=[]
          this.$commonJs.filterDataDict("riskGrade",this.gradeOptions )

        },
        mounted(){
            this.tableMainHeight = document.getElementsByClassName('table-main')[0].clientHeight - 44 //减去顶部按钮列表的高度
        }
    }
</script>

<style lang="scss" scoped>
    .table-all {
        display: flex;
        flex-direction: column;
        height: 100%;

    .search-box {
        padding-bottom: 6px;
    }

    .table-box {
        padding-top: 10px;
        flex: 1;
        display: flex;
        flex-direction: column;

    .table-main {
        flex: 1;
        overflow: auto;
    }

    .table-page {
        // padding-top: 10 px;
        // padding-bottom: 10 px;
    }

    ::v-deep .pagination-container {
        text-align: right;
    }

    }
    }
</style>
